package com.black.cat.design.create.singleton;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @description:CAS
 * @version: 1.0
 * @create：2023/1/6 13:27
 * @author：blackcat
 */
public class Singleton06 {

    private static final AtomicReference<Singleton06> INSTANCE = new AtomicReference<>();

    private Singleton06() {
    }

    public static final Singleton06 getInstance() {
        //不限次数的自旋循环，如果CAS一直失败，CPU的执行开销被消耗很严重
        for (; ; ) {
            Singleton06 instance = INSTANCE.get();
            if (null != instance) return instance;
            boolean set = INSTANCE.compareAndSet(null, new Singleton06());
            if (set) {
                return INSTANCE.get();
            }
        }
    }

}
